package com.yanqu.road.utils.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException;

import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;

public class JedisPoolHelper extends JedisPool {
    /** 连接redis失败的次数 */
    private AtomicInteger poolFailCount;

    public JedisPoolHelper(final GenericObjectPoolConfig poolConfig, final String host, int port, int timeout,
                           final String password) {
        super(poolConfig, host, port, timeout, password);
        poolFailCount = new AtomicInteger(0);
    }

    @Override
    public Jedis getResource() {
        Jedis jedis = null;
        try {
            jedis = internalPool.borrowObject();
        } catch (NoSuchElementException nse) {
            throw new JedisException("Could not get a resource from the pool", nse);
        } catch (Exception e) {
            poolFailCount.incrementAndGet();
            throw new JedisConnectionException("Could not get a resource from the pool", e);
        }
        if (jedis == null)
            jedis = super.getResource();
        else
            jedis.setDataSource(this);

        poolFailCount.set(0);
        return jedis;
    }

    public int getPoolFailCount() {
        return poolFailCount.get();
    }
}
